package com.qa.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qa.pojo.Calendars;
import com.qa.pojo.Users;
import com.qa.pojo.calendar;
import com.qa.pojo.personalEvent;
import com.qa.service.IEventService;
import com.qa.util.JsonFormatTool;

@Controller
@RequestMapping("/cal")
public class CalendarController {
	@Resource
	private IEventService eventService;

	JsonFormatTool jsonFormatTool = new JsonFormatTool();
	List<calendar> calendars = new ArrayList<calendar>();
	List<personalEvent> personalEvents = new ArrayList<personalEvent>();
	Logger logger = Logger.getLogger(this.getClass());

	/***
	 * 通过usersid导出公司内所有人的工作日志
	 */
	@RequestMapping("/monthexport")
	@ResponseBody
	public Map<String, Object> monthexport(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			int usersid = ((Users) request.getSession().getAttribute("user"))
					.getUsersid();
			Calendar date = Calendar.getInstance();
			String year = String.valueOf(date.get(Calendar.YEAR));
			String monthString = request.getParameter("month");
			int month = date.get(Calendar.MONTH);
			if (!monthString.equals("undefined")) {
				month = Integer.valueOf(monthString);
			}
			String beginmonth = String.valueOf(month);
			if (beginmonth.length() == 1) {
				beginmonth = "0" + beginmonth;
			}
			String endmonth = String.valueOf(month + 1);
			if (endmonth.length() == 1) {
				endmonth = "0" + endmonth;
			}
			beginmonth = year + "-" + beginmonth + "-01";
			endmonth = year + "-" + endmonth + "-01";
			List<Calendars> eventlist = this.eventService.exportpersonevent(
					usersid, beginmonth, endmonth);
			// 开始导出，获取模板路径
			String templatePath = request.getSession().getServletContext()
					.getRealPath("template/personalcalendars.xls");

			// 写入工作簿
			this.eventService.exportDataAll(eventlist, templatePath, response);
			resultMap.put("tag", "success");
			resultMap.put("result", "");
		} catch (Exception e) {
			resultMap.put("tag", "error");
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 通过usersID查询下属信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/selectSubordinate")
	@ResponseBody
	public Map<String, Object> selectSubordinate(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			int usersid = ((Users) request.getSession().getAttribute("user"))
					.getUsersid();
			List<Users> subordinateList = this.eventService
					.getSubordinateById(usersid);
			resultMap.put("tag", "success");
			resultMap.put("result", subordinateList);
		} catch (Exception e) {
			resultMap.put("tag", "error");
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 通过时间戳查询项目信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/selectCurrentProject")
	@ResponseBody
	public Map<String, Object> selectCurrentProject(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			List<String> projectList = this.eventService.selectCurrentProject();
			System.out.println(projectList.get(0));
			resultMap.put("tag", "success");
			resultMap.put("result", projectList);
		} catch (Exception e) {
			resultMap.put("tag", "error");
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 通过usersID查询个人事件
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/selectMyEvents")
	@ResponseBody
	public Map<String, Object> selectMyEvents(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		try {
			int usersid = ((Users) request.getSession().getAttribute("user"))
					.getUsersid();
			personalEvents = this.eventService.getPersonalEventsById(usersid);
			if (personalEvents.size() >= 0) {
				resultMap.put("tag", "success");
				resultMap.put("result", personalEvents);
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 通过calendarid查询个人日程
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/selectCalendarForOne")
	@ResponseBody
	public Map<String, Object> selectCalendarForOne(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<calendar> calendars = new ArrayList<calendar>();
		response.setStatus(200);
		try {
			int id = Integer.valueOf(request.getParameter("id"));
			calendars = this.eventService.selectCalendarForOne(id);
			if (calendars.size() >= 0) {
				resultMap.put("tag", "success");
				resultMap.put("result", calendars);
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 通过usersID查询个人日程
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/selectMyCalendar")
	@ResponseBody
	public Map<String, Object> selectMyCalendar(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<calendar> calendars = new ArrayList<calendar>();
		response.setStatus(200);
		try {

			int usersid = ((Users) request.getSession().getAttribute("user"))
					.getUsersid();
			usersid = request.getParameter("usersid") == null ? usersid
					: Integer.valueOf(request.getParameter("usersid"));
			calendars = this.eventService.selectMyCalendar(usersid);
			if (calendars.size() >= 0) {
				resultMap.put("tag", "success");
				resultMap.put("result", calendars);
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 插入个人日程单天的
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/addMyCalendarForOneDay", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addMyCalendarForOneDay(
			HttpServletRequest request, HttpServletResponse response) {
		response.setStatus(200);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean isInsert = false;
		int usersid = ((Users) request.getSession().getAttribute("user"))
				.getUsersid();
		try {
			String projectname = URLDecoder.decode(
					request.getParameter("currentprojectname"), "UTF-8");
			String work_content = URLDecoder.decode(
					request.getParameter("work_content"), "UTF-8");
			Double work_time = Double
					.valueOf(request.getParameter("work_time"));
			String date = request.getParameter("date");
			date = date.replace("Z", " UTC");// 注意是空格+UTC
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date newDate = sdf.parse(date);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(newDate);
			calendar.set(calendar.get(Calendar.YEAR),
					calendar.get(Calendar.MONTH),
					calendar.get(Calendar.DAY_OF_MONTH) + 1);
			newDate = calendar.getTime();
			date = (new SimpleDateFormat("yyyy-MM-dd")).format(newDate);
			isInsert = this.eventService.addMyCalendarForOne(usersid, date,
					projectname, work_time, work_content);

			if (isInsert == true) {
				int currentId = this.eventService.selectThisCalendarForOne(
						usersid, date, projectname, work_time, work_content);
				if (currentId >= 1) {
					resultMap.put("tag", "success");
					resultMap.put("id", currentId);
				} else {
					resultMap.put("tag", "error");
				}
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 插入个人日程
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/addMyCalendar", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addMyCalendar(HttpServletRequest request,
			HttpServletResponse response) {
		response.setStatus(200);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean isInsert = false;
		int usersid = ((Users) request.getSession().getAttribute("user"))
				.getUsersid();
		try {
			String title = URLDecoder.decode(request.getParameter("title"),
					"UTF-8");
			// 默认1，是否的意思
			int allDay = request.getParameter("allDay").equals("true") ? 0 : 1;
			String date = request.getParameter("start");
			date = date.replace("Z", " UTC");// 注意是空格+UTC
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date newDate = sdf.parse(date);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(newDate);
			calendar.set(calendar.get(Calendar.YEAR),
					calendar.get(Calendar.MONTH),
					calendar.get(Calendar.DAY_OF_MONTH) + 1);
			newDate = calendar.getTime();
			date = (new SimpleDateFormat("yyyy-MM-dd")).format(newDate);
			isInsert = this.eventService.addMyCalendar(usersid, title, allDay,
					date);

			if (isInsert == true) {
				int currentId = this.eventService.selectThisCalendar(usersid,
						title, allDay, date);
				if (currentId >= 1) {
					resultMap.put("tag", "success");
					resultMap.put("id", currentId);
				} else {
					resultMap.put("tag", "error");
				}
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 将个人事件插入到数据库中
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/insertMyEvents", method = RequestMethod.POST)
	@ResponseBody
	public boolean insertHis(HttpServletRequest request,
			HttpServletResponse response) {
		response.setStatus(200);
		boolean isInsert = false;
		int usersid = ((Users) request.getSession().getAttribute("user"))
				.getUsersid();
		try {
			String title = URLDecoder.decode(request.getParameter("title"),
					"UTF-8");
			// 根据传过来的值选择两种方式的任一种，目前不知道规律
			/*
			 * his.setResult(new
			 * String(request.getParameter("result").toString()
			 * .getBytes("iso8859_1"), "utf-8"));
			 */
			isInsert = this.eventService.insertMyEvents(usersid, title);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return isInsert;
	}

	/**
	 * 删除个人事件
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/deleteMyEvents", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteMyEvents(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		int usersid = ((Users) request.getSession().getAttribute("user"))
				.getUsersid();
		try {
			String title = URLDecoder.decode(request.getParameter("title"),
					"UTF-8");
			// 根据传过来的值选择两种方式的任一种，目前不知道规律
			/*
			 * his.setResult(new
			 * String(request.getParameter("result").toString()
			 * .getBytes("iso8859_1"), "utf-8"));
			 */
			int deleteEventsCount = this.eventService.deleteMyEvents(usersid,
					title);
			if (deleteEventsCount >= 1) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 删除个人日程
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/deleteMyCalendar", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteMyCalendar(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		int usersid = ((Users) request.getSession().getAttribute("user"))
				.getUsersid();
		try {
			int id = Integer.valueOf(request.getParameter("id"));
			int deleteMyCalendarCount = this.eventService.deleteMyCalendar(
					usersid, id);
			if (deleteMyCalendarCount >= 1) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 编辑个人日程，为了拖动
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/updateMyCalendarForDrop", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateMyCalendarForDrop(
			HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		int usersid = ((Users) request.getSession().getAttribute("user"))
				.getUsersid();
		try {
			int id = Integer.valueOf(request.getParameter("id"));
			int dayDelta = Integer.valueOf(request.getParameter("dayDelta"));
			int deleteMyCalendarCount = this.eventService
					.updateMyCalendarForDrop(usersid, id, dayDelta);
			if (deleteMyCalendarCount >= 1) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}

	/**
	 * 编辑个人日程，改变日程大小
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/updateMyCalendarForResize", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updateMyCalendarForResize(
			HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		response.setStatus(200);
		int usersid = ((Users) request.getSession().getAttribute("user"))
				.getUsersid();
		try {
			int id = Integer.valueOf(request.getParameter("id"));
			int dayDelta = Integer.valueOf(request.getParameter("dayDelta"));
			int deleteMyCalendarCount = this.eventService
					.updateMyCalendarForResize(usersid, id, dayDelta);
			if (deleteMyCalendarCount >= 1) {
				resultMap.put("tag", "success");
			} else {
				resultMap.put("tag", "error");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return resultMap;
	}
}